package org.zk.dubbo_consumer.util;

/**
 * 163邮箱工具类（高顺）
 */

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class MailUtil {

    //参数是收件人地址
    public static int sendMail(String addressee){
        int mail_code = (int)((Math.random()*9+1)*100000);
        // 发件人账号和密码
        String MY_EMAIL_ACCOUNT = "gs_1233211234567@163.com";
        String MY_EMAIL_PASSWORD = "gs19980709f";// 密码,是你自己的设置的授权码
        // SMTP服务器(这里用的163 SMTP服务器)
        String MEAIL_163_SMTP_HOST = "smtp.163.com";
        String SMTP_163_PORT = "25";// 端口号,这个是163使用到的;QQ的应该是465或者875
        // 收件人
        String RECEIVE_EMAIL_ACCOUNT = addressee;
        Properties p = new Properties();
        p.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST);
        p.setProperty("mail.smtp.port", SMTP_163_PORT);
        p.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT);
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY");

        Session session = Session.getInstance(p, new Authenticator() {
            // 设置认证账户信息
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
            }
        });
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
       try{
           // 发件人
           message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT));
           // 收件人
           message.setRecipients(Message.RecipientType.TO, RECEIVE_EMAIL_ACCOUNT);
           //抄送人
           message.setRecipients(Message.RecipientType.CC, MY_EMAIL_ACCOUNT);

           //主题
           message.setSubject("主题:南瓜课堂提醒您");
           // 内容
           message.setContent("您的验证码为："+mail_code+"请及时登录", "text/html;charset=UTF-8");
           message.setSentDate(new Date());
           message.saveChanges();
           Transport.send(message);
       }catch (Exception e){
           e.printStackTrace();
       }
       return mail_code;
    }

}
